package com.pancoit.bdsdkdemo;

import android.annotation.SuppressLint;
import android.app.Application;
import android.os.AsyncTask;
import android.widget.EditText;
import android.widget.Toast;

import com.pancoit.bdsdkdemo.base.BaseActivity;
import com.pancoit.bdsdkdemo.entity.dao.SessionDao;
import com.pancoit.bdsdkdemo.entity.dao.UserMessageDao;
import com.pancoit.bdsdkdemo.handler.BeidouSDKHandler;
import com.pancoit.bdsdklibrary.manage.BeidouSDKManage;

import net.tsz.afinal.FinalDb;

import java.util.concurrent.atomic.AtomicInteger;

import static android.widget.Toast.makeText;
import static com.pancoit.bdsdkdemo.constant.TerminalParams.frequency;
import static com.pancoit.bdsdkdemo.constant.TerminalParams.sentWaitSec;

/**
 * 主程序入口
 */
public class MainApp extends Application {
    private static MainApp mainApp;
    private Toast mToast;
    //当前所显示的Activity
    public BaseActivity mActivity;
    // 一个非专业人员的懒惰
    public EditText instruct;

    @Override
    public void onCreate() {
        super.onCreate();
        mainApp = this;
        //注册北斗应急终端SDK
        BeidouSDKManage.register(this);
        //初始化北斗处理程序
        BeidouSDKHandler.getInstance().initializeListener();
    }

    public static MainApp getInstance() {
        return mainApp;
    }

    /*******************************************(FinalDb)******************************************************/

    private static FinalDb db = null;

    public FinalDb getDb() {
        if (db == null) {
            db = FinalDb.create(this, "bdsdkdemo.db", true, 1, dbUpdateListener);
        }
        SessionDao.getInstance();
        UserMessageDao.getInstance();
        return db;
    }

    private FinalDb.DbUpdateListener dbUpdateListener = (db, oldVersion, newVersion) -> {
        if (oldVersion != newVersion) {
            switch (newVersion) {

                default:
                    break;
            }
        }
    };

    /**
     * 更新数据库版本
     *
     * @param db
     *//*
    private void updateToSevenVersion(SQLiteDatabase db) {
        db.beginTransaction();
        db.execSQL("alter table xxx add column xxx varchar(20)");
        db.setTransactionSuccessful();
        db.endTransaction();
    }*/

    /*******************************************(只是单纯的强迫症想分割一下)******************************************************/

    private static AtomicInteger atomicInteger;

    /**
     * 发送倒计时
     */
    @SuppressLint("StaticFieldLeak")
    public void startNewSentWaitSecTimer() {
        if (sentWaitSec != 0) {
            // 防止在不空闲的时候产生新的倒计时线程，这样会混乱计时器
            return;
        }
        new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                // 设置频度
                if (frequency != -1) {
                    sentWaitSec = frequency;
                } else {
                    sentWaitSec = 60;
                }
                atomicInteger = new AtomicInteger(sentWaitSec);
                while (true) {
                    if (sentWaitSec < 0) {
                        sentWaitSec = 0;
                    }
                    if (sentWaitSec == 0) {
                        return false;
                    }
                    // 自减（安全线程）
                    sentWaitSec = atomicInteger.decrementAndGet();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            protected void onPostExecute(Boolean result) {
                super.onPostExecute(result);
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    /**
     * Toast的工具方法
     *
     * @param msg
     */
    public void showMsg(final String msg) {
        mActivity.runOnUiThread(() -> {
            if (null == mToast) {
                mToast = makeText(mActivity, msg, Toast.LENGTH_SHORT);
            } else {
                mToast.setText(msg);
            }
            mToast.show();
        });
    }
}
